#include <clusnet/net/SyncTcpClient.h>
#include <iostream>

int main(int argc, char* argv[])
{
    try
    {
        if (argc < 3)
        {
            std::cerr << "Usage: SyncTcpClient_test <host> <port>" << std::endl;
            return 1;
        }

        clusnet::net::SyncTcpClient   client;
        boost::system::error_code ec;
        client.connect(ec, argv[1], argv[2], std::chrono::seconds(5));
        if (ec)
        {
            std::cerr << "connectc failed. " << ec.message() << std::endl;
            return 1;
        }
        std::cout << "connect to " << argv[1] << ":" << argv[2] << "success." << std::endl; 

        std::string line;
        while (std::cin >> line)
        {
            clusnet::net::TcpDataPacketStream   stream;
            stream.append(line.c_str(), line.length());
            auto data = std::make_shared<clusnet::net::TcpDataPacket>(std::move(stream).data());
            client.write(ec, data, std::chrono::seconds(5));
            if (ec)
            {
                std::cerr << "write failed. " << ec.message() << std::endl;
                return 1;
            }
            auto msg = client.read(ec, std::chrono::seconds(5));
            if (ec)
            {
                std::cerr << "read failed. " << ec.message() << std::endl;
                return 1;
            }
            std::cout << "recv msg: " << msg->body() << std::endl;
            if (line == "stop")
            {
                break;
            }
        }
        client.close();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
